package com.hcj.demo.controller;

import com.hcj.demo.dto.ExpenseDto;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.form.api.FormInfo;
import org.flowable.form.api.FormService;
import org.flowable.form.model.FormField;
import org.flowable.form.model.SimpleFormModel;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 报销单 demoController
 */
@Slf4j
@RestController
@RequestMapping(value = "expense")
public class ExpenseController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private FormService formService;


    /**
     * 添加报销单
     */
    @PostMapping("add")
    public String addExpense(@RequestBody ExpenseDto expenseDto) {
        // 1.解析报销单参数
        BeanMap beanMap = BeanMap.create(expenseDto);
        // 2.生成报销单ID（expenseId）,并保存到数据库
        // 3.把expenseId做为参数在整个流程中共享，并启动工作流
        // 4.拿到processInstanceId,并绑定到报销单中
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("Expense", beanMap);
        log.info("当前用户id: {} ", Authentication.getAuthenticatedUserId());
        log.info("processInstance = {}", processInstance);
        return "提交成功.流程Id为：" + processInstance.getId();
    }


    /**
     * 审批报销单
     *
     * @param taskId 任务ID
     * @param isPass 0驳回1通过
     */
    @GetMapping("apply")
    public String apply(@RequestParam String taskId, @RequestParam(defaultValue = "1") Boolean isPass) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        log.info("task = {}", task);
        if (task == null) {
            throw new RuntimeException("报销单任务不存在");
        }
        // 添加评论
        taskService.addComment(task.getId(), task.getProcessInstanceId(), task.getAssignee() + "做出了：" + isPass + "的判定");

        //通过审核
        HashMap<String, Object> map = new HashMap<>();
        map.put("outcome", isPass ? "通过" : "驳回");

        // 如果任务中需要用户填写表单，则按表单的形式完成任务
        String formKey = task.getFormKey();
        if (formKey != null && !"".equals(formKey)) {
            FormInfo info = taskService.getTaskFormModel(task.getId());
            if (info != null && info.getFormModel() instanceof SimpleFormModel) {
                SimpleFormModel sfm = (SimpleFormModel) info.getFormModel();
                List<FormField> fields = sfm.getFields();
                log.info("FormField===>");
                for (FormField ff : fields) {
                    log.info("id = {}", ff.getId());
                    log.info("name = {}", ff.getName());
                    log.info("type = {}", ff.getType());
                    log.info("placeholder = {}", ff.getPlaceholder());
                    log.info("value = {}", ff.getValue());
                    log.info("Params = {}", ff.getParams());
                    log.info("Layout = {}", ff.getLayout());
                    log.info("readOnly = {}", ff.isReadOnly());
                    log.info("isOverrideId = {}", ff.isOverrideId());
                    log.info("required = {}", ff.isRequired());

                }
                log.info("value from variable outcomes");
                sfm.getOutcomes().stream().forEach(x -> log.info("outcome: id = {}, name = {}", x.getId(), x.getName()));
            }


            Map<String, Object> variables = new HashMap<>();
            variables.put("input1", "这是表单中要输入的值");
            taskService.completeTaskWithForm(task.getId(), info.getId(), isPass ? "通过" : "驳回", variables);
        } else {
            taskService.complete(taskId, map);
        }


        return String.format("taskId=%s,processed %s ok!", taskId, isPass);
    }


}
